package com.uinnova.product.eam.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.google.common.collect.Lists;
import com.uinnova.product.eam.comm.model.es.AssetWarehouseDir;
import com.uinnova.product.eam.comm.model.es.EamArtifact;
import com.uinnova.product.eam.comm.model.es.EamCategory;
import com.uinnova.product.eam.comm.model.es.EamDiagramRelationSys;
import com.uinnova.product.eam.dto.AXEAClassMapping;
import com.uinnova.product.eam.dto.ArchReviewConf;
import com.uinnova.product.eam.model.cj.vo.DiagramPlanVO;
import com.uinnova.product.eam.model.enums.AssetType;
import com.uinnova.product.eam.service.*;
import com.uinnova.product.eam.service.es.AssetWarehouseDirDao;
import com.uinnova.product.eam.vo.AssertRange;
import com.uinnova.product.eam.vo.AssertRangeReq;
import com.uinnova.product.vmdb.comm.model.ci.CCcCiClass;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiClassInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CiGroupPage;
import com.uinnova.project.api.diagram.v2.client.ESDiagramApiClient;
import com.uinnova.project.base.diagram.comm.diagram.EamDiagramQuery;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uinnova.project.db.eam.ESDiagramDao;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.cmdb.base.ESCIClassInfo;
import com.uino.bean.cmdb.base.ESCIInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.query.ESCISearchBean;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import com.uino.service.cmdb.microservice.impl.CIClassSvc;
import com.uino.util.sys.SysUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.ExistsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Log4j2
public class GTDiagramServiceImpl implements GTDiagramService {

    @Autowired
    private ESDiagramApiClient diagramApiClient;
    @Autowired
    private ESDiagramDao esDiagramDao;
    @Autowired
    private AXEAConfService axeaConfService;
    @Autowired
    private CIClassSvc ciClassSvc;
    @Autowired
    private IamsCISwitchSvc ciSwitchSvc;
    @Autowired
    private EamDiagramRelationSysService  diagramRelationSysService;
    @Autowired
    private IEamArtifactSvc artifactSvc;
    @Autowired
    private EamCategorySvc categorySvc;
    @Autowired
    private AssetWarehouseDirDao assetWarehouseDirDao;
    @Resource
    private IUserApiSvc userApiSvc;

    @Value("${http.resource.space}")
    private String httpResourceUrl;

    @Override
    public long artifactUseCount(Long artifactId) {
        Assert.notNull(artifactId, "制品id不能为空");
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery("dataStatus", 1));
        query.must(QueryBuilders.termQuery("diagramSubType", 2));
        query.must(QueryBuilders.termQuery("viewType.keyword", artifactId.toString()));
        query.must(QueryBuilders.termQuery("historyVersionFlag", 1));
        return esDiagramDao.countByCondition(query);
    }

    @Override
    public List<Integer> queryDiagramReleaseVersion(String diagramId) {
        List<ESDiagram> diagrams = diagramApiClient.selectByIds(
                Collections.singletonList(diagramId), null, null);
        if (BinaryUtils.isEmpty(diagrams)) {
            return Collections.emptyList();
        }
        ESDiagram currDiagram = diagrams.get(0);
        EamDiagramQuery eamDiagramQuery = new EamDiagramQuery();
        eamDiagramQuery.setIsOpen(1);
        eamDiagramQuery.setReleaseDiagramId(currDiagram.getReleaseDiagramId());
        if (BinaryUtils.isEmpty(eamDiagramQuery.getReleaseDiagramId())) {
            eamDiagramQuery.setReleaseDiagramId(diagramId);
        }
        List<ESDiagram> diagramList = esDiagramDao.getListByCdt(eamDiagramQuery);
        diagramList.sort(Comparator.comparing(ESDiagram::getReleaseVersion).reversed());
        List<Integer> releaseVersions = new ArrayList<>();
        diagramList.forEach(d -> releaseVersions.add(diagramList.size()==1 ? 1 : d.getReleaseVersion()));
        return releaseVersions;
    }

    @Override
    public Map<String, List<AssertRange>> assertRanges(AssertRangeReq req) {
        if (req == null || StringUtils.isBlank(req.getDiagramId()) || CollectionUtils.isEmpty(req.getCiCodes())) {
            return new HashMap<>();
        }
        List<String> ciCodes = req.getCiCodes();
        List<String> assertRangeClassCodes = axeaConfService.assertRangeClassCodes();
        if (CollectionUtils.isEmpty(assertRangeClassCodes)) {
            log.info("未配置资产分类，本次不查询资产范围");
            return new HashMap<>();
        }
        CCcCiClass cdt = new CCcCiClass();
        cdt.setClassCodes(assertRangeClassCodes.toArray(new String[0]));
        List<CcCiClassInfo> ciClassInfos = ciClassSvc.queryClassByCdt(cdt);
        if (CollectionUtils.isEmpty(ciClassInfos)) {
            log.info("未查询到资产分类[{}]，本次不查询资产范围", JSON.toJSONString(assertRangeClassCodes));
            return new HashMap<>();
        }
        List<Long> ciClassIds = ciClassInfos.stream().map(ciiClassInfo ->
                ciiClassInfo.getCiClass().getId()).collect(Collectors.toList());
        ESCISearchBean bean = new ESCISearchBean();
        bean.setClassIds(ciClassIds);
        bean.setCiCodes(ciCodes);
        bean.setPageNum(1);
        bean.setPageSize(ciCodes.size());
        Page<ESCIInfo> page = ciSwitchSvc.searchESCIByBean(bean, LibType.DESIGN);
        if (CollectionUtils.isEmpty(page.getData())) {
            log.info("未查询到ci信息[ciCLassId:{}, ciCode:{}]，本次不查询资产范围", ciClassIds, ciCodes);
            return new HashMap<>();
        }
        List<String> existCiCodes = page.getData().stream().map(ESCIInfo::getCiCode).collect(Collectors.toList());
        //查绑定视图
        List<EamDiagramRelationSys> diagramByRelationSysList = diagramRelationSysService.findDiagramByRelationSysList(existCiCodes);
        if (CollectionUtils.isEmpty(diagramByRelationSysList)) {
            log.info("未查询到ciCodes绑定的视图信息，本次不查询资产范围");
            return new HashMap<>();
        }
        List<String> diagramIds = new ArrayList<>();
        Map<String, List<String>> relationDiagramMap = new HashMap<>();
        for (EamDiagramRelationSys relationSys : diagramByRelationSysList) {
            String diagramEnergy = relationSys.getDiagramEnergy();
            if (StringUtils.isBlank(diagramEnergy)) {
                continue;
            }
            diagramIds.add(diagramEnergy);
            List<String> dIds = relationDiagramMap.getOrDefault(relationSys.getEsSysId(), new ArrayList<>());
            dIds.add(diagramEnergy);
            relationDiagramMap.put(relationSys.getEsSysId(), dIds);
        }
        if (CollectionUtils.isEmpty(diagramIds)) {
            log.info("未查询到ciCodes绑定的视图信息，本次不查询资产范围");
            return new HashMap<>();
        }
        Set<String> filterDiagramIds = new HashSet<>();
        List<ESDiagram> filterDiagrams = diagramApiClient.queryDBDiagramInfoByIds(new String[]{req.getDiagramId()});
        if (!CollectionUtils.isEmpty(filterDiagrams)) {
            //私有库的图不过滤，资产库的视图过滤本身
            filterDiagramIds = filterDiagrams.stream()
                    .filter(d -> d.getIsOpen() != null && d.getIsOpen() == 1)
                    .map(ESDiagram::getDEnergy).collect(Collectors.toSet());
        }

        diagramIds.removeIf(filterDiagramIds::contains);
        if (CollectionUtils.isEmpty(diagramIds)) {
            return new HashMap<>();
        }

        //查视图信息
        BoolQueryBuilder diagramQuery = QueryBuilders.boolQuery();
        diagramQuery.must(QueryBuilders.termQuery("dataStatus", 1));
        diagramQuery.must(QueryBuilders.termQuery("status", 1));
        diagramQuery.must(QueryBuilders.termQuery("historyVersionFlag", 1));
        diagramQuery.must(QueryBuilders.termQuery("domainId", 1L));
        diagramQuery.must(QueryBuilders.termQuery("isOpen", 1));
        diagramQuery.must(QueryBuilders.termsQuery("dEnergy.keyword", diagramIds));

        List<ESDiagram> diagrams = esDiagramDao.getListByQuery(diagramQuery);
        if (!CollectionUtils.isEmpty(diagrams)) {
            Set<String> finalFilterDiagramIds = filterDiagramIds;
            diagrams = diagrams.stream().filter(d -> d.getIsOpen() != null && d.getIsOpen() == 1
                    && !finalFilterDiagramIds.contains(d.getDEnergy())).collect(Collectors.toList());
            diagrams.forEach(e -> {
                e.setIcon1(httpResourceUrl + e.getIcon1());
            });
        }
        if (CollectionUtils.isEmpty(diagrams)) {
            log.info("未查询到ciCodes绑定的视图信息[{}]，本次不查询资产范围", JSON.toJSONString(diagrams));
            return new HashMap<>();
        }
        Map<String, ESDiagram> diagramMap = diagrams.stream().collect(Collectors.toMap(ESDiagram::getDEnergy, Function.identity()));
        //查系统文件夹
        List<EamCategory> categories = categorySvc.getDesignByCiCodes(existCiCodes);
        Map<String, EamCategory> sysDirMap = new HashMap<>();
        Map<String, AssetWarehouseDir> rootDirMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(categories)) {
            sysDirMap = categories.stream().collect(Collectors.toMap(EamCategory::getCiCode, Function.identity()));
            Map<Long, AssetWarehouseDir> rootDirIdAssetWarehouseDirMap = new HashMap<>();
            for (EamCategory category : categories) {
                Long rootDirId = getRootDirId(category);
                if (rootDirId == null) {
                    continue;
                }
                if (rootDirIdAssetWarehouseDirMap.containsKey(rootDirId)) {
                    rootDirMap.put(category.getCiCode(), rootDirIdAssetWarehouseDirMap.get(rootDirId));
                    continue;
                }
                WildcardQueryBuilder query = QueryBuilders.wildcardQuery("moduleUrl.keyword", "*" + rootDirId + "*");
                List<AssetWarehouseDir> list = assetWarehouseDirDao.getListByQuery(query);
                if (!CollectionUtils.isEmpty(list)) {
                    rootDirMap.put(category.getCiCode(), list.get(0));
                    rootDirIdAssetWarehouseDirMap.put(rootDirId, list.get(0));
                }
            }
        }

        //查制品信息
        List<Long> artifactIds = diagrams.stream().map(e ->
                BinaryUtils.isEmpty(e.getViewType()) ? 0L : Long.parseLong(e.getViewType())).collect(Collectors.toList());
        List<EamArtifact> artifacts = artifactSvc.queryArtifactSimpleInfo(artifactIds);
        Map<Long, EamArtifact> artifactMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(artifacts)) {
            artifactMap = artifacts.stream().collect(Collectors.toMap(EamArtifact::getId, Function.identity()));
        }

        Map<String, List<AssertRange>> result = new HashMap<>();
        for (String ciCode : ciCodes) {
            if (!existCiCodes.contains(ciCode)) {
                result.put(ciCode, new ArrayList<>());
                continue;
            }
            List<String> bindDiagramIds = relationDiagramMap.get(ciCode);
            if (CollectionUtils.isEmpty(bindDiagramIds)) {
                result.put(ciCode, new ArrayList<>());
                continue;
            }
            List<AssertRange> assertRanges = new ArrayList<>();
            for (String diagramId : bindDiagramIds) {
                if (!diagramMap.containsKey(diagramId)) {
                    continue;
                }
                ESDiagram diagram = diagramMap.get(diagramId);
                AssertRange assertRange = new AssertRange();
                assertRange.setCiCode(ciCode);
                assertRange.setDiagramId(diagramId);
                assertRange.setDiagramName(diagram.getName());
                assertRange.setDiagramIcon(diagram.getIcon1());
                assertRange.setModifyTime(diagram.getModifyTime());
                Long artifactId = BinaryUtils.isEmpty(diagram.getViewType()) ? 0L : Long.parseLong(diagram.getViewType());
                if (artifactMap.containsKey(artifactId)) {
                    EamArtifact artifact = artifactMap.get(artifactId);
                    assertRange.setArtifactId(artifact.getId());
                    assertRange.setArtifactName(artifact.getArtifactName());
                }
                if (sysDirMap.containsKey(ciCode) && rootDirMap.containsKey(ciCode)) {
                    assertRange.setLibraryId(rootDirMap.get(ciCode).getId());
                    assertRange.setSystemDirId(sysDirMap.get(ciCode).getId());
                }
                assertRanges.add(assertRange);
            }
            assertRanges.sort(Comparator.comparing(AssertRange::getModifyTime).reversed());
            result.put(ciCode, assertRanges);
        }
        return result;
    }

    @Override
    public Page<DiagramPlanVO> getAllDiagrams(JSONObject jsonObject) {
        Page<DiagramPlanVO> result = new Page<>();
        String pageNum = jsonObject.getString("pageNum");
        String pageSize = jsonObject.getString("pageSize");
        Asserts.notNull(pageNum, "pageNum");
        Asserts.notNull(pageSize, "pageSize");
        result.setPageNum(Long.parseLong(pageNum));
        result.setPageSize(Long.parseLong(pageSize));

        List<DiagramPlanVO> diagramPlanList = new ArrayList<>();
        BoolQueryBuilder diagramQuery = QueryBuilders.boolQuery();
        diagramQuery.must(QueryBuilders.termQuery("dataStatus", 1));
        diagramQuery.must(QueryBuilders.termQuery("status", 1));
        diagramQuery.must(QueryBuilders.termQuery("historyVersionFlag", 1));
        // 视图类型 1:普通视图 3: 公共模板 4:个人模板
        diagramQuery.must(QueryBuilders.termsQuery("diagramType", Lists.newArrayList(1,2,3,4)));
        diagramQuery.must(QueryBuilders.termQuery("isOpen", 0));
        diagramQuery.must(QueryBuilders.existsQuery("ownerCode"));

        // 查询条件
        String name = jsonObject.getString("name");
        String creators = jsonObject.getString("creators");
        String viewType = jsonObject.getString("viewType");
        // 视图状态 0：未发布，1：已发布，2：审批中，3：审核中可编辑
        String releaseStatus = jsonObject.getString("releaseStatus");
        // 关联资产分类-classId
        String queryCiClassId = jsonObject.getString("ciClassId");
        // 关联资产-ciCode
        String queryCiCode = jsonObject.getString("ciCode");

        if (!BinaryUtils.isEmpty(name)) {
            BoolQueryBuilder nameOrCiQuery = QueryBuilders.boolQuery();
            nameOrCiQuery.should(QueryBuilders.wildcardQuery("name.keyword", "*" + name.trim() + "*"));
            // 如果name不为空 需要根据name查询关联资产列表
            if (!BinaryUtils.isEmpty(name)) {
                List<CcCiInfo> ciList = getCiListByName(name);
                if (!BinaryUtils.isEmpty(ciList)) {
                    List<String> ciCodesByName = ciList.stream().map(ciInfo -> ciInfo.getCi().getCiCode()).collect(Collectors.toList());
                    List<EamDiagramRelationSys> diagramRelations = diagramRelationSysService.findDiagramByRelationSysList(ciCodesByName);
                    Set<String> queryDEnergies = diagramRelations.stream().map(EamDiagramRelationSys::getDiagramEnergy).collect(Collectors.toSet());
                    if (!BinaryUtils.isEmpty(queryDEnergies)) {
                        nameOrCiQuery.should(QueryBuilders.termsQuery("dEnergy.keyword", queryDEnergies));
                    }
                }
            }
            diagramQuery.must(nameOrCiQuery);
        }
        if (!BinaryUtils.isEmpty(creators)) {
            List<String> creatorList = JSON.parseObject(creators, new TypeReference<List<String>>(){});
            if (!BinaryUtils.isEmpty(creatorList)) {
                diagramQuery.must(QueryBuilders.termsQuery("ownerCode.keyword", creatorList));
            }
        }
        if (!BinaryUtils.isEmpty(viewType)) {
            //自由视图
            if (viewType.equals("0")) {
                diagramQuery.mustNot(QueryBuilders.existsQuery("viewType"));
            } else {
                diagramQuery.must(QueryBuilders.termQuery("viewType.keyword", viewType));
            }
        }
        if (!BinaryUtils.isEmpty(releaseStatus)) {
            BoolQueryBuilder flowStatusCondition = QueryBuilders.boolQuery()
                    .should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("flowStatus")))
                    .should(QueryBuilders.termQuery("flowStatus", 0))
                    .minimumShouldMatch(1); // 满足任意一个条件即可
            switch (releaseStatus) {
                case "0":
                    diagramQuery.must(flowStatusCondition);
                    // 构建复合条件：releaseDiagramId不存在、为空字符串或为null
                    BoolQueryBuilder releaseDiagramCondition = QueryBuilders.boolQuery()
                            .should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("releaseDiagramId")))
                            .should(QueryBuilders.termQuery("releaseDiagramId.keyword", ""))
                            .minimumShouldMatch(1); // 满足任意一个条件即可
                    diagramQuery.must(releaseDiagramCondition);
                    break;
                case "1":
                    diagramQuery.must(flowStatusCondition);
                    // 创建一个exists查询用于releaseDiagramId存在的条件
                    ExistsQueryBuilder existsQuery = QueryBuilders.existsQuery("releaseDiagramId");
                    diagramQuery.must(existsQuery);
                    diagramQuery.mustNot(QueryBuilders.termQuery("releaseDiagramId.keyword", ""));
                    break;
                case "2":
                    diagramQuery.must(QueryBuilders.termQuery("flowStatus", 2));
                    break;
                case "3":
                    diagramQuery.must(QueryBuilders.termQuery("flowStatus", 1));
                    break;
                default :
                    break;
            }
        }

        if (!BinaryUtils.isEmpty(queryCiCode)) {
            // 如果ciCode不为空 则不用关心classId是否有值 只根据确定的ciCode查询即可
            List<EamDiagramRelationSys> diagramRelations = diagramRelationSysService.findDiagramRelationSysList(queryCiCode);
            Set<String> queryDEnergies = diagramRelations.stream().map(EamDiagramRelationSys::getDiagramEnergy).collect(Collectors.toSet());
            if (!BinaryUtils.isEmpty(queryDEnergies)) {
                diagramQuery.must(QueryBuilders.termsQuery("dEnergy.keyword", queryDEnergies));
            } else {
                log.info("根据ciCode未查询到关联视图！");
                result.setTotalRows(0l);
                result.setTotalPages(0l);
                result.setData(diagramPlanList);
                return result;
            }
        } else if (!BinaryUtils.isEmpty(queryCiClassId)){
            // ciCode为空 classId不为空 则需要根据分类id查询所有的ci列表 再根据ci列表查询所有关联的视图id
            List<ESCIInfo> esCiInfos = getCiListByClassId(Long.valueOf(queryCiClassId));
            List<String> ciCodesByClass = esCiInfos.stream().map(ESCIInfo::getCiCode).collect(Collectors.toList());
            List<EamDiagramRelationSys> diagramRelations = diagramRelationSysService.findDiagramByRelationSysList(ciCodesByClass);
            Set<String> queryDEnergies = diagramRelations.stream().map(EamDiagramRelationSys::getDiagramEnergy).collect(Collectors.toSet());
            if (!BinaryUtils.isEmpty(queryDEnergies)) {
                diagramQuery.must(QueryBuilders.termsQuery("dEnergy.keyword", queryDEnergies));
            } else {
                log.info("根据classId未查询到关联视图！");
                result.setTotalRows(0l);
                result.setTotalPages(0l);
                result.setData(diagramPlanList);
                return result;
            }

        }
        List<SortBuilder<?>> sorts = new LinkedList<>();
        sorts.add(SortBuilders.fieldSort("modifyTime").order(SortOrder.DESC));
        Page<ESDiagram> diagramPage = esDiagramDao.getSortListByQuery(Integer.valueOf(pageNum), Integer.valueOf(pageSize), diagramQuery, sorts);
        if(BinaryUtils.isEmpty(diagramPage.getData())){
            result.setTotalRows(0l);
            result.setTotalPages(0l);
            result.setData(diagramPlanList);
            return result;
        }

        List<ESDiagram> data = new ArrayList<>();
        Set<String> ownerCodes = new HashSet<>();
        Set<Long> artifactIds = new HashSet<>();
        List<String> dEnergies = new ArrayList<>();
        for (ESDiagram each : diagramPage.getData()) {
            data.add(each);
            if(!BinaryUtils.isEmpty(each.getOwnerCode())){
                ownerCodes.add(each.getOwnerCode());
            }
            if(!BinaryUtils.isEmpty(each.getViewType())){
                artifactIds.add(Long.parseLong(each.getViewType()));
            }
            if(!BinaryUtils.isEmpty(each.getDEnergy())){
                dEnergies.add(each.getDEnergy());
            }
        }

        //根据制品id制品，再与视图一一匹配。
        List<EamArtifact> eamArtifacts = artifactSvc.queryArtifactListByIds(Lists.newArrayList(artifactIds), 1);
        Map<Long, EamArtifact> artifactMap = eamArtifacts.stream().collect(Collectors.toMap(EamArtifact::getId, each -> each, (k1, k2) -> k1));

        // 查询用户信息
        Map<String, SysUser> userMap = queryUserMap(ownerCodes);

        // 查询关联资产 再与视图做匹配
        Map<String, String> diagramSysMap = new HashMap<>();// 视图id-资产ciCode
        Map<String, ESCIInfo> ciCodeMap = new HashMap<>(); // ciCode-ci
        Map<Long, String> ciClassMap = new HashMap<>();// ciClassId-ciClassName
        List<EamDiagramRelationSys> diagramRelations = diagramRelationSysService.getEamDiagramRelationSys(dEnergies);
        if (!BinaryUtils.isEmpty(diagramRelations)) {
            List<String> esSysIds = diagramRelations.stream().map(EamDiagramRelationSys::getEsSysId).collect(Collectors.toList());
            diagramSysMap = diagramRelations.stream().collect(Collectors.toMap(EamDiagramRelationSys::getDiagramEnergy, EamDiagramRelationSys::getEsSysId, (k1, k2) -> k1));
            List<ESCIInfo> ciList = ciSwitchSvc.getCiByCodes(esSysIds, null, LibType.DESIGN);
            ciCodeMap = ciList.stream().collect(Collectors.toMap(ESCIInfo::getCiCode, e -> e, (k1, k2) -> k2));
            List<Long> classIds = ciList.stream().map(ESCIInfo::getClassId).collect(Collectors.toList());
            List<ESCIClassInfo> classInfos = ciClassSvc.queryESClassInfoByIds(classIds);
            ciClassMap = classInfos.stream().collect(Collectors.toMap(ESCIClassInfo::getId, ESCIClassInfo::getClassName));
        }
        for (ESDiagram each : data) {
            DiagramPlanVO diagram = new DiagramPlanVO();
            diagram.setAssetType(AssetType.DIAGRAM);
            diagram.setDiagram(each);
            diagram.setCreator(userMap.get(each.getOwnerCode()));
            if(BinaryUtils.isEmpty(each.getReleaseDiagramId())){
                diagram.setReleaseStatus(0);
            }else{
                diagram.setReleaseStatus(1);
            }
            if (!BinaryUtils.isEmpty(each.getFlowStatus())) {
                if (!each.getFlowStatus().equals(0)) {
                    if (Objects.equals(each.getFlowStatus(), 1)) {
                        diagram.setReleaseStatus(3);
                    } else {
                        diagram.setReleaseStatus(2);
                    }
                }
            }
            if (!BinaryUtils.isEmpty(each.getViewType())) {
                //查询视图中绑定的制品类型分类
                EamArtifact artifact = artifactMap.get(Long.valueOf(each.getViewType()));
                if(!BinaryUtils.isEmpty(artifact)){
                    diagram.setArtifactType(artifact.getTypeClassification());
                    diagram.getDiagram().setDirType(artifact.getTypeClassification());
                }
            }
            // 视图关联资产绑定
            diagram.setCiName("-");
            diagram.setCiClassName("-");
            String ciCode = diagramSysMap.get(each.getDEnergy());
            if (!BinaryUtils.isEmpty(ciCode)) {
                ESCIInfo ciInfo = ciCodeMap.get(ciCode);
                if (!BinaryUtils.isEmpty(ciInfo)) {
                    String className = ciClassMap.get(ciInfo.getClassId());
                    diagram.setCiName(getSysName(ciInfo));
                    diagram.setCiClassName(className);
                }
            }

            diagram.setCreateTime(each.getCreateTime());
            diagram.setModifyTime(each.getModifyTime());
            diagramPlanList.add(diagram);
        }
        result.setTotalRows(diagramPage.getTotalRows());
        result.setTotalPages(diagramPage.getTotalPages());
        result.setData(diagramPlanList);
        return result;
    }

    private List<ESCIInfo> getCiListByClassId(Long classId) {
        List<ESCIInfo> result = new ArrayList<>();
        int pageNum = 1;
        int pageSize = 1000;
        ESCISearchBean bean = new ESCISearchBean();
        bean.setClassIds(Collections.singletonList(classId));
        bean.setPageNum(pageNum);
        bean.setPageSize(pageSize);
        bean.setDomainId(SysUtil.getCurrentUserInfo().getDomainId());
        Page<ESCIInfo> page = ciSwitchSvc.searchESCIByBean(bean, LibType.DESIGN);
        if (!BinaryUtils.isEmpty(page.getData())) {
            result.addAll(page.getData());
        }
        for (int i = 2; i <= page.getTotalPages(); i++ ) {
            bean.setPageNum(i);
            page = ciSwitchSvc.searchESCIByBean(bean, LibType.DESIGN);
            if (!CollectionUtils.isEmpty(page.getData())) {
                result.addAll(page.getData());
            }
        }
        return result;
    }

    private List<CcCiInfo> getCiListByName(String name) {
        ArchReviewConf archReviewConf = axeaConfService.getArchReviewConf();
        //无label字段时返回空
        List<String> labelDefs = getLabelDefs(archReviewConf.getProjectClassId());
        if (CollectionUtils.isEmpty(labelDefs)) {
            return null;
        }
        AXEAClassMapping axeaClassMapping = axeaConfService.getSystemClassMapping();
        labelDefs = getLabelDefs(axeaClassMapping.getSystemClassId());
        if (CollectionUtils.isEmpty(labelDefs)) {
            return null;
        }
        List<CcCiInfo> result = new ArrayList<>();
        int pageNum = 1;
        int pageSize = 50;
        ESCISearchBean bean = new ESCISearchBean();
        bean.setSortField("modifyTime");
        bean.setAsc(false);
        bean.setWordLabel(true);
        bean.setWords(Arrays.asList(name));
        bean.setClassIds(Arrays.asList(archReviewConf.getProjectClassId(), axeaClassMapping.getSystemClassId()));
        bean.setDomainId(1L);
        bean.setPageNum(pageNum);
        bean.setPageSize(pageSize);
        CiGroupPage page = ciSwitchSvc.queryPageBySearchBean(bean, false, LibType.DESIGN);
        if (!CollectionUtils.isEmpty(page.getData())) {
            result.addAll(page.getData());
        }
        for (int i = 2; i <= page.getTotalPages(); i++ ) {
            bean.setPageNum(i);
            page = ciSwitchSvc.queryPageBySearchBean(bean, false, LibType.DESIGN);
            if (!CollectionUtils.isEmpty(page.getData())) {
                result.addAll(page.getData());
            }
        }
        return result;
    }

    private List<String> getLabelDefs(Long classId) {
        ESCIClassInfo classInfo = ciClassSvc.queryESClassInfoById(classId);
        if (BinaryUtils.isEmpty(classInfo)) {
            return new ArrayList<>();
        }
        List<String> defs = new ArrayList<>();
        classInfo.getCcAttrDefs().forEach(def -> {
            if (def.getIsCiDisp() != null && def.getIsCiDisp() == 1) {
                defs.add(def.getProStdName());
            }
        });
        return defs;
    }

    private String getSysName(ESCIInfo esciInfo) {
        String ciLabel = esciInfo.getCiLabel();
        List<String> datas = JSONObject.parseArray(ciLabel, String.class);
        if (!BinaryUtils.isEmpty(ciLabel) && !CollectionUtils.isEmpty(datas)) {
            String[] strings1 = datas.toArray(new String[0]);
            return StringUtils.join(strings1, ",");
        }

        return formatSysName(esciInfo.getCiPrimaryKey());
    }

    private String formatSysName(String ciPrimaryKey) {
        List<String> strings = JSONObject.parseArray(ciPrimaryKey, String.class);
        if (!CollectionUtils.isEmpty(strings)) {
            strings.remove(0);
            String[] strings1 = strings.toArray(new String[0]);
            return StringUtils.join(strings1, ",");
        }
        return null;
    }

    /**
     * 获取用户信息map
     * @param codes 用户code
     */
    private Map<String, SysUser> queryUserMap(Collection<String> codes) {
        CSysUser cSysUser = new CSysUser();
        cSysUser.setLoginCodes(codes.toArray(new String[0]));
        cSysUser.setSuperUserFlags(new Integer[]{0, 1});
        List<SysUser> userList = userApiSvc.getSysUserByCdt(cSysUser);
        Map<String, SysUser> userIdObjMap = new HashMap<>(userList.size());
        for (SysUser user : userList) {
            user.setLoginPasswd(null);
            String icon = user.getIcon();
            if (icon != null && !icon.startsWith(this.httpResourceUrl)) {
                user.setIcon(httpResourceUrl + icon);
            }
            userIdObjMap.put(user.getLoginCode(), user);
        }
        return userIdObjMap;
    }

    private Long getRootDirId(EamCategory category) {
        String[] dirIds = category.getDirPath().split("#");
        if (dirIds.length < 2) {
            return null;
        }
        try {
            return Long.valueOf(dirIds[1]);
        } catch (Exception e) {
            return null;
        }
    }
}
